package com.pla.googlecalendarviews;

import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.TableCellEditor;

public class ColorPicker extends AbstractCellEditor
        implements TableCellEditor,
        ActionListener {

  private final ColorPicker colorPicker = this;
  private final String EDIT = "edit";
  private Color color = Color.WHITE;
  private JButton button = new JButton();
  private JDialog dialog = new JDialog();
  private JPanel panel = new JPanel(new GridLayout(0, 7));
  private String lookAndFeel = UIManager.getLookAndFeel().getName();

  public ColorPicker() {
    dialog.setTitle("Color Picker");
    dialog.setModal(true);
    Utils.makeDisposeOnEscapeKey(dialog);
    button.setActionCommand(EDIT);
    button.addActionListener(this);
    button.setBorderPainted(false);
    String[] colors = CalendarDAO.colors;
    for (int i = 0; i < colors.length; i++) {
      JButton colorButton = new JButton();
      colorButton.setActionCommand(colors[i]);
      colorButton.setBackground(Color.decode(colors[i]));
      if (lookAndFeel.startsWith("GTK")) { // Bug workaround
        colorButton.setText(colors[i]);
        colorButton.setForeground(Color.decode(colors[i]));
      }
      colorButton.setBorderPainted(false);
      colorButton.addActionListener(this);
      panel.add(colorButton);
    }
    dialog.setContentPane(panel);
    dialog.pack();

  }

  public Object getCellEditorValue() {
    return color;
  }

  public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    if (value != null) {
      color = (Color) value;
      button.setBackground(color);
    }
    return button;
  }

  public void actionPerformed(ActionEvent e) {
    String actionCommand = e.getActionCommand();
    System.out.println("actionPerformed " + actionCommand);
    if (EDIT.equals(actionCommand)) {
      button.setBackground(color);
      dialog.setLocationRelativeTo(button);
      dialog.setVisible(true);
      fireEditingStopped();
    } else {
      color = Color.decode(actionCommand);
      dialog.dispose();
    }
  }
}
